/**
 * 性能监控工具
 * 用于监控应用性能指标，帮助优化首屏加载时间
 */

interface PerformanceMetrics {
  fcp: number; // First Contentful Paint
  lcp: number; // Largest Contentful Paint
  fid: number; // First Input Delay
  cls: number; // Cumulative Layout Shift
  ttfb: number; // Time to First Byte
  domLoad: number; // DOM 加载时间
  resourceLoad: number; // 资源加载时间
}

class PerformanceMonitor {
  private metrics: PerformanceMetrics = {
    fcp: 0,
    lcp: 0,
    fid: 0,
    cls: 0,
    ttfb: 0,
    domLoad: 0,
    resourceLoad: 0
  };

  private observers: PerformanceObserver[] = [];

  constructor() {
    this.initObservers();
    this.measureInitialLoad();
  }

  private initObservers() {
    // 监控 FCP (First Contentful Paint)
    if ('PerformanceObserver' in window) {
      const fcpObserver = new PerformanceObserver((list) => {
        const entries = list.getEntries();
        const fcpEntry = entries[entries.length - 1];
        this.metrics.fcp = fcpEntry.startTime;
        console.log('FCP:', this.metrics.fcp);
      });
      fcpObserver.observe({ entryTypes: ['paint'] });

      // 监控 LCP (Largest Contentful Paint)
      const lcpObserver = new PerformanceObserver((list) => {
        const entries = list.getEntries();
        const lcpEntry = entries[entries.length - 1];
        this.metrics.lcp = lcpEntry.startTime;
        console.log('LCP:', this.metrics.lcp);
      });
      lcpObserver.observe({ entryTypes: ['largest-contentful-paint'] });

      // 监控 FID (First Input Delay)
      const fidObserver = new PerformanceObserver((list) => {
        const entries = list.getEntries();
        const fidEntry = entries[entries.length - 1];
        this.metrics.fid = fidEntry.processingStart - fidEntry.startTime;
        console.log('FID:', this.metrics.fid);
      });
      fidObserver.observe({ entryTypes: ['first-input'] });

      // 监控 CLS (Cumulative Layout Shift)
      const clsObserver = new PerformanceObserver((list) => {
        let clsValue = 0;
        for (const entry of list.getEntries()) {
          if (!entry.hadRecentInput) {
            clsValue += (entry as any).value;
          }
        }
        this.metrics.cls = clsValue;
        console.log('CLS:', this.metrics.cls);
      });
      clsObserver.observe({ entryTypes: ['layout-shift'] });

      this.observers = [fcpObserver, lcpObserver, fidObserver, clsObserver];
    }
  }

  private measureInitialLoad() {
    // 测量 TTFB (Time to First Byte)
    const navigationEntry = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming;
    if (navigationEntry) {
      this.metrics.ttfb = navigationEntry.responseStart - navigationEntry.requestStart;
      this.metrics.domLoad = navigationEntry.domContentLoadedEventEnd - navigationEntry.domContentLoadedEventStart;
      this.metrics.resourceLoad = navigationEntry.loadEventEnd - navigationEntry.loadEventStart;
    }

    // 监控资源加载
    this.monitorResourceLoading();
  }

  private monitorResourceLoading() {
    const resourceObserver = new PerformanceObserver((list) => {
      for (const entry of list.getEntries()) {
        const resourceEntry = entry as PerformanceResourceTiming;
        if (resourceEntry.initiatorType === 'script' || resourceEntry.initiatorType === 'css') {
          console.log(`Resource loaded: ${resourceEntry.name}`, {
            duration: resourceEntry.duration,
            size: resourceEntry.transferSize,
            type: resourceEntry.initiatorType
          });
        }
      }
    });
    resourceObserver.observe({ entryTypes: ['resource'] });
  }

  // 获取性能指标
  public getMetrics(): PerformanceMetrics {
    return { ...this.metrics };
  }

  // 检查性能是否达标
  public checkPerformance(): { passed: boolean; issues: string[] } {
    const issues: string[] = [];
    
    if (this.metrics.fcp > 2000) {
      issues.push('FCP 超过 2 秒，建议优化首屏渲染');
    }
    
    if (this.metrics.lcp > 2500) {
      issues.push('LCP 超过 2.5 秒，建议优化最大内容绘制');
    }
    
    if (this.metrics.fid > 100) {
      issues.push('FID 超过 100ms，建议优化交互响应');
    }
    
    if (this.metrics.cls > 0.1) {
      issues.push('CLS 超过 0.1，建议优化布局稳定性');
    }

    return {
      passed: issues.length === 0,
      issues
    };
  }

  // 清理观察器
  public destroy() {
    this.observers.forEach(observer => observer.disconnect());
  }
}

// 创建全局性能监控实例
export const performanceMonitor = new PerformanceMonitor();

// 导出性能监控工具函数
export const measurePerformance = () => {
  return performanceMonitor.getMetrics();
};

export const checkPerformance = () => {
  return performanceMonitor.checkPerformance();
};

// 页面可见性变化监控
export const monitorVisibilityChange = () => {
  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'visible') {
      console.log('页面变为可见，重新检查性能');
      const metrics = measurePerformance();
      const check = checkPerformance();
      console.log('当前性能指标:', metrics);
      console.log('性能检查结果:', check);
    }
  });
}; 